<template>
  <div class="ellipsis">
    <el-tooltip
      :disabled="isShowTip"
      :effect="effect"
      :enterable="enterable"
      :placement="placement"
      :content="tooltipContent || content"
      :visible-arrow="visibleArrow"
      v-bind="$attrs"
    >
      <div class="over-flow" @mouseover="onMouseOver(refName)">
        <span @click="handleClick" :ref="(el) => setRef(el, refName)">
          {{ content || ' ' }}
        </span>
      </div>
    </el-tooltip>
  </div>
</template>

<script lang="ts" setup>
// import { ElTooltip } from 'element-plus'

const props = defineProps({
  // 常规显示的文字内容
  content: {
    type: String,
    default: ''
  },
  // tooltip 显示的文字内容
  tooltipContent: {
    type: String,
    default: ''
  },
  // 为页面文字标识（如在同一页面中调用多次组件，此参数不可重复）
  refName: {
    type: String,
    default: 'myEllipsis'
  },
  // Tooltip 的出现位置
  placement: {
    type: String,
    default: 'top'
  },
  // 主题色 dark/light
  effect: {
    type: String,
    default: 'light'
  },
  // 鼠标是否可进入到 tooltip 中
  enterable: {
    type: Boolean,
    default: false
  },
  // 是否显示 箭头
  visibleArrow: {
    type: Boolean,
    default: true
  }
})
const emit = defineEmits(['handleClick'])

const isShowTip = ref(true)
const refs: Record<string, Ref<HTMLElement | null>> = {}

const setRef = (el: HTMLElement | null, name: string) => {
  if (refs[name]) {
    refs[name].value = el
  } else {
    refs[name] = ref(el)
  }
}

const handleClick = () => {
  emit('handleClick')
}

const onMouseOver = (refName: string) => {
  const ref = refs[refName]
  if (ref && ref.value) {
    const parentWidth = ref.value.parentNode?.offsetWidth || 0
    const contentWidth = ref.value.offsetWidth
    // 判断是否开启tooltip
    isShowTip.value = contentWidth <= parentWidth
  }
}
</script>

<style lang="scss" scoped>
.ellipsis {
  .over-flow {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    margin: 0;
  }
}
</style>
